package models

import (
	"context"
	"fmt"
	"strings"
)

func (m *defaultRelationModel) DeleteRelation(ctx context.Context, fromID, toID int64) error {
	var resp Relation
	query := fmt.Sprintf("select %s from %s where `user_id` = ? and `to_user_id` = ? limit 1", relationRows, m.table)
	err := m.QueryRowNoCacheCtx(ctx, &resp, query, fromID, toID)
	if err != nil {
		return err
	}
	return m.Delete(ctx, resp.Id)
}

func (m *defaultRelationModel) FriendListByPage(ctx context.Context, userID, offset, limit int64) ([]int64, error) {
	var userIds []int64
	query := fmt.Sprintf(
		"select a.to_user_id from %s as a join %s as b "+
			"on (a.user_id = b.to_user_id and a.to_user_id = b.user_id) "+
			"where a.user_id = %d limit ? offset ?", m.table, m.table, userID)
	err := m.QueryRowsNoCacheCtx(ctx, &userIds, query, limit, offset)
	if err != nil {
		return nil, err
	}
	return userIds, nil
}

func (m *defaultRelationModel) FollowListByPage(ctx context.Context, fromID, offset, limit int64) ([]int64, error) {
	var userIds []int64
	query := fmt.Sprintf("select to_user_id from %s where delete_time = 0 and `user_id` = %d limit ? offset ?", m.table, fromID)
	err := m.QueryRowsNoCacheCtx(ctx, &userIds, query, limit, offset)
	if err != nil {
		return nil, err
	}
	return userIds, nil
}

func (m *defaultRelationModel) FanListByPage(ctx context.Context, toID, offset, limit int64) ([]int64, error) {
	var userIds []int64
	query := fmt.Sprintf("select user_id from %s where delete_time = 0 and `to_user_id` = %d limit ? offset ?", m.table, toID)
	err := m.QueryRowsNoCacheCtx(ctx, &userIds, query, limit, offset)
	if err != nil {
		return nil, err
	}
	return userIds, nil
}

func (m *defaultUserModel) UserList(ctx context.Context, userIds []int64) ([]*User, error) {
	if len(userIds) == 0 {
		return nil, nil
	}

	var anySlice []any
	for _, id := range userIds {
		anySlice = append(anySlice, id)
	}

	placeholders := make([]string, len(userIds))
	for i := range userIds {
		placeholders[i] = "?"
	}
	placeholderStr := strings.Join(placeholders, ",")
	var users []*User
	query := fmt.Sprintf("select %s from %s where delete_time = 0 and `id` in (%s)", userRows, m.table, placeholderStr)
	err := m.QueryRowsNoCacheCtx(ctx, &users, query, anySlice...)
	if err != nil {
		return nil, err
	}
	return users, nil
}
